//头文件
#include <stdio.h>
#include <sys/types.h> //open write头文件
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h> //strlen 头文件
#include <unistd.h>//access 函数头文件
#include "gpio_dir.h"

int fd5; //文件描述符
int len5;
int ret5;
char gpio_path5[100];

//gpio从内核空间导出到应用空间
//相当于命令echo 138 > export
int gpio_export5(char *argv){
    
    fd5 = open("/sys/class/gpio/export",O_WRONLY);

    if(fd5 < 0){
        printf("open /sys/class/gpio/export error\n");
        return -1;
    }

    len5 = strlen(argv);
    ret5 = write(fd5,argv,len5); //写入138
    if(ret5 < 0){
        printf("write /sys/class/gpio/export error\n");
        return -2;
    }
    close(fd5);
}

//取消gpio从内核空间导出到应用空间
//相当于命令echo 138 > unexport
int gpio_unexport5(char *argv){
    
    fd5 = open("/sys/class/gpio/unexport",O_WRONLY);

    if(fd5 < 0){
        printf("open /sys/class/gpio/unexport error\n");
        return -1;
    }
    len5 = strlen(argv);//计算字符串长度
    ret5 = write(fd5,argv,len5); //写入138
    if(ret5 < 0){
        printf("write /sys/class/gpio/unexport error\n");
        return -2;
    }
    close(fd5);
}

//设置gpio,传入两个参数，方向和值
int gpio_ctrl5(char *arg, char *val)
{
    char file_path[100];//存放路径
    sprintf(gpio_path5,"/sys/class/gpio/gpio%s","138");//sprintf函数，拼接
    sprintf(file_path,"%s/%s",gpio_path5,arg);//获取路径，涉及到参数的传递，这里gpiopath为138
   
    fd5 = open(file_path,O_WRONLY);

    if(fd5 < 0){
        printf("out ctrl open file_path error\n");
        return -1;
    }
    len5 = strlen(val);
    ret5 = write(fd5,val,len5); //写入138
    if(ret5 < 0){
        printf("write file_path error\n");
        return -2;
    }
    close(fd5);
}

//放到主函数里面
void gpio_init138(char *va)//va代表着传入的值，1还是0(能设置电机的正反转)
{
    //首先，判断该gpio138是否已经导出用户空间
   //sprintf(gpio_path5,"/sys/class/gpio/gpio%s","138");//sprintf函数，拼接
    
    if (access((gpio_path5),F_OK))//新面孔access函数
    {
        /* code */
        gpio_export5("138");//这里的argv[1]代表着传入的gpio引脚
    }
    //else{
      //  gpio_unexport("138");
    //}
    gpio_ctrl5("direction","out");
    gpio_ctrl5("value",va);//写1，还是写0

}